
#include "thread.h"

int recvn(int sockfd, void *buf, int length){
    int total = 0; 
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,0);
        total += sret;
    }
    return 0;
}


int registerAcc(int netfd,MYSQL* mysql){

    char user_name[256];
    char passwd[100];
    int check =0;

    train_t registerInfo;
    bzero(&registerInfo,sizeof(train_t));
    recv(netfd,&registerInfo.length, sizeof(int),MSG_WAITALL);
    recv(netfd,registerInfo.buf, registerInfo.length,MSG_WAITALL);
    remove_trailing_invisible_chars(registerInfo.buf);

    int len=strlen(registerInfo.buf);
    printf("len = %d\n",len);
    //读取传入的用户名
    strcpy(user_name,registerInfo.buf);
    printf("接收的用户名:%s\n",user_name);
    char sql_order[1024];
    sprintf(sql_order,"select tomb from user where name = '%s';",user_name);
    int len_order=strlen(sql_order);
    printf("len_order = %d\n",len_order);
    printf("order = %s\n",sql_order);
    int myret=mysql_query(mysql,sql_order);
    if(myret!=0){
        fprintf(stderr,"mysql_query:%s\n", mysql_error(mysql));
    }
    printf("myret = %d\n",myret);

    MYSQL_RES *result=mysql_store_result(mysql);
    int ROWS =mysql_num_rows(result);
    if(ROWS!=0)//
    {
        printf("用户已存在\n");
        check =-1;
        send(netfd,&check, sizeof(int), MSG_NOSIGNAL);
        return 0;
    }
    printf("用户不存在\n");
    check=0;
    send(netfd,&check,sizeof(int),MSG_NOSIGNAL);
    printf("check = %d\n",check);

    bzero(&registerInfo,sizeof(train_t));
    recvn(netfd, &registerInfo.length, sizeof(registerInfo.length));
    recvn(netfd, registerInfo.buf, registerInfo.length);

    remove_trailing_invisible_chars(registerInfo.buf);
    strncpy(passwd,registerInfo.buf,registerInfo.length);
    printf("接收的密码:%s\n",passwd);

    generateFormattedSalt(registerInfo.buf,23);
    char *cipher=crypt(passwd,registerInfo.buf);
    //开始注册
    char sql_reg[1024];
    sprintf(sql_reg,"insert into user(name,salt,ciphertext,tomb) values('%s','%s','%s',0);",user_name,registerInfo.buf,cipher);

    mysql_query(mysql,sql_reg);//插入注册信息

    char order[1024];
    sprintf(order,"insert into df_mes (fileName,path,user,parID,md5,tomb) \
            values('/','/','%s',-1,0,0);", \
            user_name);
    mysql_query(mysql, order);

    check = 0;

    //向客户端发送check值通知客户端已经注册成功
    send(netfd,&check,sizeof(int),MSG_NOSIGNAL);
    return 0;
}




